/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.icanci.snowstack.statecase;

import cn.icanci.snowstack.Action;
import cn.icanci.snowstack.CommonMachineExecute;
import cn.icanci.snowstack.statecase.exception.StateInvalidActionException;

import java.util.Objects;

/**
 * @author icanci
 * @date Created in 2021/05/23 22:16
 * @version 1.0
 */
public class StateEntranceMachine implements CommonMachineExecute {

    private StateEntranceMachineState locked   = new LockedStateEntranceMachineState();

    private StateEntranceMachineState unlocked = new UnlockedStateEntranceMachineState();

    private StateEntranceMachineState state;

    public StateEntranceMachine(StateEntranceMachineState state) {
        this.state = state;
    }

    @Override
    public String execute(Action action) {
        if (Objects.isNull(action)) {
            throw new StateInvalidActionException();
        }
        StateAction stateAction = (StateAction) action;
        if (StateAction.PASS.equals(stateAction)) {
            return state.pass(this);
        }
        return state.insertCoin(this);
    }

    public boolean isUnlocked() {
        return state == unlocked;
    }

    public boolean isLocked() {
        return state == locked;
    }

    public String open() {
        setState(unlocked);
        return "opened";
    }

    public String alarm() {
        setState(locked);
        return "alarm";
    }

    public String refund() {
        setState(unlocked);
        return "refund";
    }

    public String close() {
        setState(locked);
        return "closed";
    }

    private void setState(StateEntranceMachineState state) {
        this.state = state;
    }
}
